package com.maoye.ossp.biz.statement.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.hotent.base.api.query.QueryFilter;
import com.hotent.base.api.query.QueryOP;
import com.maoye.ossp.biz.brand.entity.Supplier;
import com.maoye.ossp.biz.brand.service.ISupplierService;
import com.maoye.ossp.biz.contract.entity.AdvertAssbrands;
import com.maoye.ossp.biz.contract.entity.AdvertAssociated;
import com.maoye.ossp.biz.contract.entity.Assbrands;
import com.maoye.ossp.biz.contract.entity.AssociatedContract;
import com.maoye.ossp.biz.contract.entity.LeaseAssbrands;
import com.maoye.ossp.biz.contract.entity.LeaseAssociated;
import com.maoye.ossp.biz.contract.entity.MarketAssbrands;
import com.maoye.ossp.biz.contract.entity.MarketAssociated;
import com.maoye.ossp.biz.contract.entity.SelfAssbrands;
import com.maoye.ossp.biz.contract.entity.SelfAssociated;
import com.maoye.ossp.biz.contract.service.IAdvertAssociatedService;
import com.maoye.ossp.biz.contract.service.IContractService;
import com.maoye.ossp.biz.contract.service.ILeaseAssContractService;
import com.maoye.ossp.biz.contract.service.IMarketAssociatedService;
import com.maoye.ossp.biz.contract.service.ISelfAssociatedService;
import com.maoye.ossp.biz.statement.entity.BizStatementCasualExp;
import com.maoye.ossp.biz.statement.entity.BizStatementPaymentDetail;
import com.maoye.ossp.biz.statement.entity.BizStatementStmCounter;
import com.maoye.ossp.biz.statement.entity.BizStatementStmPrepaid;
import com.maoye.ossp.biz.statement.entity.StatementInvoice;
import com.maoye.ossp.biz.statement.service.IBizStatementCasualExpService;
import com.maoye.ossp.biz.statement.service.IBizStatementPaymentDetailService;
import com.maoye.ossp.biz.statement.service.IBizStatementStmCounterService;
import com.maoye.ossp.biz.statement.service.IBizStatementStmErrorService;
import com.maoye.ossp.biz.statement.util.BizStatementConstant;
import com.maoye.ossp.biz.statement.util.excel.ExcelOperatorConstant;
import com.maoye.ossp.biz.statement.util.excel.JExcelOperator;
import com.maoye.ossp.common.entity.Page;
import com.maoye.ossp.common.web.BaseController;
import com.maoye.ossp.sys.base.entity.SysBaseFloor;
import com.maoye.ossp.sys.base.entity.SysBaseShop;
import com.maoye.ossp.sys.base.service.SysBaseFloorService;
import com.maoye.ossp.sys.base.service.SysBaseShopService;
import com.maoye.ossp.sys.org.util.UserUtils;
import com.maoye.sc.api.domain.User;
import com.maoye.sc.service.user.UserServiceImpl;

/**
 * 结算对账-专柜 Controller
 * 
 * @author yangyf
 * 
 *         2014年2月17日
 */
@Controller
@RequestMapping(value = "/biz/statement/stm/counter/")
public class BizStatementStmCounterController extends BaseController {
	@Resource
	private IBizStatementStmCounterService stmCounterService;

	@Resource
	private IBizStatementPaymentDetailService paymentDetailService;

	@Resource
	private IBizStatementStmErrorService stmErrorService;

	@Resource
	private IBizStatementCasualExpService statementCasualExpService;
	
	
	@Resource
	private SysBaseShopService sysBaseShopService ;
	
	@Resource
	private SysBaseFloorService sysBaseFloorService ;
	
	@Resource
	private ISupplierService supplierService;
	
	@Resource
	private UserServiceImpl userServiceImpl;
	
	@Resource
	private IContractService contractService;
	
	@Resource
	private IAdvertAssociatedService advertAssociatedService;
	
	@Resource
	private ILeaseAssContractService leaseAssContractService;
	
	@Resource
	private ISelfAssociatedService selfAssociatedService;
		
	@Resource
	private IMarketAssociatedService marketAssociatedService;

	/**
	 * 界面显示
	 * 
	 * @param stmCounter
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "list")
	public String list(BizStatementStmCounter stmCounter,
			HttpServletRequest request, Model model) {
		//获取登陆用户Id 
		Long userId=UserUtils.getCurrentUserId();
		//根据当前用户Id 如果是供应商 获取用户获取供应商信息
		Supplier supplier=supplierService.get(userId);
		QueryFilter queryFilter = getQuerFilter(request, stmCounter);//设置供应商编码
		String isSupplier="0";
		if(supplier!=null){
			queryFilter.addFilter("supplierNo", supplier.getSupplierNo(), QueryOP.EQUAL);
			isSupplier="1";

		}
		Page<BizStatementStmCounter> page = (Page<BizStatementStmCounter>) stmCounterService
				.find(queryFilter);
		List<BizStatementStmCounter> list = page.getList();
		if (list != null) {
			for (BizStatementStmCounter counter : list) {
				if(counter!=null){
					// 联营合同
					if(counter.getContractType().equals("Z100")){
						Map map=contractService.getBrandByContractNo(counter.getContractNumber());
						if(map!=null){
						Assbrands brand=(Assbrands) map.get("brand");
						if(brand!=null){
						 counter.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
							 counter.setCateName(brand.getCmcate().getCateName());
						   }
						}//自营合同
					  }
					}else if(counter.getContractType().equals("Z300")||counter.getContractType().equals("Z400")){
						Map map=selfAssociatedService.getBrandByContractNo(counter.getContractNumber());
						if(map!=null){
						SelfAssbrands brand=(SelfAssbrands) map.get("brand");
						if(brand!=null){
						counter.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
							 counter.setCateName(brand.getCmcate().getCateName());
						   }
						 }
						}
					}else if(counter.getContractType().equals("Z200")){
						Map map=leaseAssContractService.getBrandByContract(counter.getContractNumber());
						if(map!=null){
						LeaseAssbrands brand=(LeaseAssbrands) map.get("brand");
						if(brand!=null){
						counter.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
							 counter.setCateName(brand.getCmcate().getCateName());
						   }
						 }
						}
					}else if(counter.getContractType().equals("Z500")){
						Map map=advertAssociatedService.getBrandByContractNo(counter.getContractNumber());
						if(map!=null){
						AdvertAssbrands brand=(AdvertAssbrands) map.get("brand");
						if(brand!=null){
						counter.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
							 counter.setCateName(brand.getCmcate().getCateName());
						   }
						 }
						}
					}else if(counter.getContractType().equals("Z600")){
						Map map=marketAssociatedService.getBrandByContractNo(counter.getContractNumber());
						if(map!=null){
						MarketAssbrands brand=(MarketAssbrands) map.get("brand");
						if(brand!=null){
						counter.setMainBrand(brand.getBrandCName());
						 if(brand.getCmcate()!=null){
							 counter.setCateName(brand.getCmcate().getCateName());
						   }
						 }
						}
				}
			}
		}
	}
		page.setList(list);
		model.addAttribute("page", page);
		model.addAttribute("stmCounter", stmCounter);
		model.addAttribute("isSupplier", isSupplier);
		return resultPage("/biz/statement/counter/counterList", model, request);
	}

	/**
	 * 查看详细信息
	 * 
	 * @param id
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/view")
	public String view(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String id=request.getParameter("id");
		String billNo=request.getParameter("billNo");
		Map map=new HashMap();
	    String companyCode=request.getParameter("companyCode");
	    String year=request.getParameter("year");
		/*  Long userId=UserUtils.getCurrentUserId();
	      User user= userServiceImpl.getUserById(String.valueOf(userId));
		String flag="0";
			if(user!=null&& user.getUserType().equals("SUPPLIER")){
				 flag="1";
			}*/
		map.put("companyCode", companyCode);
		map.put("billNo",billNo);
		map.put("year", year);
		BizStatementStmCounter stmCounter = stmCounterService.get(id);
		List<BizStatementPaymentDetail> paymentDetailList=paymentDetailService.getDetailList(map);
		if(paymentDetailList!=null){
			stmCounter.setStatementPaymentDetails(paymentDetailList);
		}
		model.addAttribute("stmCounter", stmCounter);
		/*model.addAttribute("flag",flag);*/
		return "/biz/statement/counter/counterView";
	}

	/**
	 * 打印
	 * 
	 * @param id
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{id}/print")
	public String print(@PathVariable String id, HttpServletRequest request,
			HttpServletResponse response, Model model) {
		String billNo=request.getParameter("billNo");
	    String companyCode=request.getParameter("companyCode");
	    String year=request.getParameter("year");
		Map map=new HashMap();

		map.put("companyCode", companyCode);
		map.put("billNo",billNo);
		map.put("year", year);
		BizStatementStmCounter stmCounter = stmCounterService.get(id);
		List<BizStatementPaymentDetail> paymentDetailList=paymentDetailService.getDetailList(map);
		if(paymentDetailList!=null){
			stmCounter.setStatementPaymentDetails(paymentDetailList);
		}
		
		model.addAttribute("stmCounter", stmCounter);
		return "/biz/statement/counter/print";
	}

	/**
	 * 导出专柜结算对账单条数据
	 * 
	 * @param billNo
	 *            参数
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "{billNo}/exportCounter")
	public void exportCounter(@PathVariable String billNo,
			HttpServletRequest request, HttpServletResponse response) {
		List<BizStatementStmCounter> list = new ArrayList<BizStatementStmCounter>();
		BizStatementStmCounter stmCounter = stmCounterService.getByBill(billNo);

		list.add(stmCounter);
		JExcelOperator jExcelOperator = new JExcelOperator();

		// 导出到excel,并将导出文件发往客户端
		jExcelOperator.exportExcel(request, response,
				ExcelOperatorConstant.COLUMN_STATEMENTCOUNTER,
				ExcelOperatorConstant.FIELD_STATEMENTCOUNTER, list);
	}

	/**
	 * 扣款明细 显示
	 * 
	 * @param billNo
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{billNo}/getPaymentBill")
	public String getPaymentBill(@PathVariable String billNo,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		BizStatementPaymentDetail paymentDetail = paymentDetailService
				.getDetailBill(billNo);
		model.addAttribute("paymentDetail", paymentDetail);
		return "/biz/statement/counter/paymentDetailView";
	}

	/**
	 * 按条件查询 结算起始日期 供应商 是否确认结算
	 * 
	 * @param statementStmCounter
	 *            参数
	 * @param request
	 * @param response
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "getBy")
	public String getBy(BizStatementStmCounter statementStmCounter,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Map map = new HashMap();
		map.put("isReconciliation", statementStmCounter.getIsReconciliation());
		map.put("startTime", statementStmCounter.getStartTime());
		map.put("endTime", statementStmCounter.getEndTime());
		map.put("supplierNo", statementStmCounter.getSupplierNo());
		List<BizStatementStmCounter> list = stmCounterService.getByAll(map);
		model.addAttribute("list", list);
		return "/biz/statement/counter/counterList";
	}

	/**
	 * 确认结算对账
	 * 
	 * @param request
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value = "{billNo}/confirm")
	public String confirm(@PathVariable String billNo,
			HttpServletRequest request, RedirectAttributes redirectAttributes,
			Model model) {
		BizStatementStmCounter stmCounter = stmCounterService.getByBill(billNo);
		Map map = new HashMap();
		map.put("id", stmCounter.getId());
		map.put("isReconciliation", BizStatementConstant.IS_RECONCILIATION);
		stmCounterService.confirm(map);
		List<BizStatementStmCounter> list = stmCounterService.getList(map);
		model.addAttribute("list", list);
		addMessage(redirectAttributes, "结算对账成功");
		return "/biz/statement/counter/counterList";
	}


	/**
	 * 查看临时费用
	 * 
	 * @param id
	 *            参数
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "{debitDetailId}/getByCasualExpId")
	public String getByCasualExpId(@PathVariable String debitDetailId,
			Model model) {

		BizStatementCasualExp statementCasualExp = statementCasualExpService
				.getByPId(debitDetailId);
		model.addAttribute("statementCasualExp", statementCasualExp);
		return "/biz/statement/casualexp/view";
	}

	/**
	 * 联营专柜 供应商开票
	 * 
	 * @param model
	 * 
	 * @param id
	 *            参数
	 * @return 添加开票的页面
	 */
	@RequestMapping(value = "{id}/addInvoice")
	public String addInvoice(Model model, @PathVariable String id) {
		StatementInvoice invoice = new StatementInvoice();
		BizStatementStmCounter statementCounter=null;
		if (StringUtils.isNotEmpty(id)) {
			statementCounter = stmCounterService.get(id);
			if (statementCounter != null) {
				//获取不动产号 ,不动产号里面有门店，楼层的信息
				String counters=statementCounter.getCounters();
				String []strArray=counters.split("\\.");
				String shopCode=null;
				String floorCode=null;
				if(strArray!=null&&strArray.length>0){
					Map map=new HashMap();
					shopCode=strArray[0];
					floorCode=strArray[2];
					map.put("code", shopCode);
					SysBaseShop shop=sysBaseShopService.getShopById(map);
					if(shop!=null){
						invoice.setRegionCode(shop.getRegionCode());
					}
					Map map1=new HashMap();
					map1.put("shopCode",shopCode);
					map1.put("code",floorCode);
					SysBaseFloor floor =sysBaseFloorService.getFloorById(map1);
					if(floor!=null){
						invoice.setFloorName(floor.getName());
					}
					invoice.setShopCode(shopCode);
					//设置楼层编码
					invoice.setDeptId(floorCode);
				}
				 String taxRate="";
				 String taxType="";
				 String taxRateCode="";
				if(statementCounter.getContractType().equals("Z100")){
					Map map=contractService.getBrandByContractNo(statementCounter.getContractNumber().substring(5));
					if(map!=null){
				    AssociatedContract associatedContract=(AssociatedContract) map.get("contract");
				    if(associatedContract!=null){
					taxRate=associatedContract.getTaxRate();
					taxRateCode=associatedContract.getTaxRateCode();
					taxType=associatedContract.getTaxType();
				    }
					}//自营合同
				}else if(statementCounter.getContractType().equals("Z300")||statementCounter.getContractType().equals("Z400")){
					Map map=selfAssociatedService.getBrandByContractNo(statementCounter.getContractNumber().substring(5));
					if(map!=null){
						SelfAssociated selfAssociated=(SelfAssociated) map.get("contract");
						if(selfAssociated!=null){
						taxRate=selfAssociated.getTaxRate();
						taxRateCode=selfAssociated.getTaxRateCode();
						taxType=selfAssociated.getTaxType();
						}

					}
				}else if(statementCounter.getContractType().equals("Z200")){
					Map map=leaseAssContractService.getBrandByContract(statementCounter.getContractNumber().substring(5));
					if(map!=null){
						LeaseAssociated leaseAssociated=(LeaseAssociated) map.get("contract");
						if(leaseAssociated!=null){
						taxRate=leaseAssociated.getTaxRate();
						taxRateCode=leaseAssociated.getTaxRateCode();
						taxType=leaseAssociated.getTaxType();
						}

					}
				}else if(statementCounter.getContractType().equals("Z500")){
					Map map=advertAssociatedService.getBrandByContractNo(statementCounter.getContractNumber().substring(5));
					if(map!=null){
						AdvertAssociated advertAssociated=(AdvertAssociated) map.get("contract");
						if(advertAssociated!=null){
						taxRate=advertAssociated.getTaxRate();
						taxRateCode=advertAssociated.getTaxRateCode();
						taxType=advertAssociated.getTaxType();
						}

					}
				}else if(statementCounter.getContractType().equals("Z600")){
					Map map=marketAssociatedService.getBrandByContractNo(statementCounter.getContractNumber().substring(5));
					if(map!=null){
						MarketAssociated marketAssociated=(MarketAssociated) map.get("contract");
						if(marketAssociated!=null){
						taxRate=marketAssociated.getTaxRate();
						taxRateCode=marketAssociated.getTaxRateCode();
						taxType=marketAssociated.getTaxType();
						}

					}
			}
				if(taxRateCode.equals("R0")){
					invoice.setTaxRateCode("J0");
				}else if(taxRateCode.equals("R1")){
					invoice.setTaxRateCode("J1");
				}else if(taxRateCode.equals("R2")){
					invoice.setTaxRateCode("J4");
				}else if(taxRateCode.equals("R3")){
					invoice.setTaxRateCode("J5");
				}
				if(taxRate.equals("0")){
					invoice.setTaxRateName(taxRate+"%"+taxType);
					}else{
						invoice.setTaxRateName(taxRate+taxType);

					}
				if(taxRate.equals("17%")){
					invoice.setTaxRate(17.0);
				}else if(taxRate.equals("13%")){
					invoice.setTaxRate(13.0);
				}
				
				invoice.setSupplierNo(statementCounter.getSupplierNo());
				invoice.setSupplierName(statementCounter.getSupplierName());
				invoice.setStartDate(statementCounter.getStartTime());
				invoice.setEndDate(statementCounter.getEndTime());
				invoice.setBillingAmount(statementCounter.getActualCost() == null ? 0.0
						: statementCounter.getActualCost().doubleValue());
				invoice.setBillNo(statementCounter.getBillNo());
				invoice.setInvoiceType(statementCounter.getContractType());
				invoice.setCompanyCode(statementCounter.getCompanyCode());
				invoice.setYear(statementCounter.getYear());
				invoice.setContractNumber(statementCounter.getContractNumber());
				invoice.setBillId(Long.parseLong(id));
			}
		}
		if(statementCounter!=null){
			 model.addAttribute("isReconciliation",statementCounter.getIsReconciliation());
		}
		model.addAttribute("statementInvoice", invoice);
		String flag="1";//联营结算对账
		model.addAttribute("flag",flag);
		return "/biz/statement/invoice/supplies/add";
	}
}
